﻿using System;
using System.Collections.Generic;
using System.Text;

namespace _2022Learning._03DesignPattern
{
    /// <summary>
    /// 3.1 饿汉式单例
    /// 类一加载，对象就初始化到内存中
    /// </summary>
    public class SingletonPattern1
    {
        // 声明私有只读静态对象为程序锁
        private static readonly object Singleton_Lock = new object();

        //声明私有静态变量存储对象信息
        private static volatile SingletonPattern1 _instance = null;

        /// <summary>
        /// 静态构造函数
        /// 由CLR保证，程序第一次使用这个类型前被调用，且只调用一次
        /// </summary>
        static SingletonPattern1()
        {
            _instance = new SingletonPattern1();
        }

        /// <summary>
        /// 获取单例实例
        /// </summary>
        /// <returns></returns>
        public static SingletonPattern1 GetInstance()
        {
            return _instance;
        }


    }


    /// <summary>
    /// 3.2 懒汉式单例
    /// 在使用的时候才会把对象存入到内存中
    /// </summary>
    public class SingletonPattern2
    {
        // 声明私有只读静态对象为程序锁
        private static readonly  object Singleton_Lock = new object();
        //声明私有静态变量存储对象信息
        private static volatile SingletonPattern2 _instance = null;
        /// <summary>
        /// 私有化构造函数
        /// </summary>
        private SingletonPattern2()
        {

        }

        /// <summary>
        /// 获取单例实例
        /// 双if加锁
        /// </summary>
        /// <returns></returns>
        public static SingletonPattern2 GetInstance()
        {
            // 最外层的一个if盘点是为了减轻锁的引入带来的额外的开销
            if (_instance == null)
            {
                // 锁是为了解决多线程的问题
                lock (Singleton_Lock)
                {
                    if (_instance == null)
                    {
                        _instance = new SingletonPattern2();
                    }
                }
            }
            return _instance;
        }
    }
}
